﻿/*
 * Netkill
 * 
 * Copyright © 2012 John Granström. All Rights Reserved.
 * 
 * This software is released under the terms and conditions of the BSD license. See 'license.txt' for details.'
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Management;
using System.Net.NetworkInformation;

namespace Netkill
{
    public class Interfacer
    {
        bool isKilled = false;
        private NetworkInterface[] livingInterfaces;

        public NetworkInterface[] LivingInterfaces
        {
            get
            {
                return this.livingInterfaces;
            }
        }

        public bool IsKilled
        {
            get
            {
                return this.isKilled;
            }
        }

        public Interfacer()
        {
            livingInterfaces = GetPotentialInterfaces();
        }

        private NetworkInterface[] GetPotentialInterfaces()
        {
            return NetworkInterface.GetAllNetworkInterfaces().Where(i => i.OperationalStatus == OperationalStatus.Up
                && (i.NetworkInterfaceType == NetworkInterfaceType.Ethernet || i.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)).ToArray<NetworkInterface>();
        }

        public void DisableLivingInterfaces()
        {
            isKilled = true;
            MapOverLivingInterfaces(obj => obj.InvokeMethod("Disable", null));
        }

        public void EnableLivingInterfaces()
        {
            isKilled = false;
            MapOverLivingInterfaces(obj => obj.InvokeMethod("Enable", null));
        }

        private void MapOverLivingInterfaces(Func<ManagementObject, object> f)
        {
            ManagementClass managementClass = new ManagementClass("Win32_NetworkAdapter");
            ManagementObjectCollection mgmtObjectColl = managementClass.GetInstances();

            foreach (ManagementObject mgmtObject in mgmtObjectColl)
            {
                if (livingInterfaces.Any(r => r.Id != null && r.Id.Equals(mgmtObject["GUID"])))
                {
                    f(mgmtObject);
                }
            }
        }
    }
}
